package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.DateUtils;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    //根据年月查询对应的预约设置数据
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month) {
        //判断是否为空
        if (month == null || month.length() == 0) {
            log.error("年月不能为空");
            throw new RuntimeException("年月不能为空");
        }
        //判断传进来的年月份是否合法
        try {
            DateUtils.getMonthBetween(month, month, "yyyy-MM");
        } catch (Exception e) {
            log.error("年月格式不正确: {}", e.getMessage(), e);
            throw new RuntimeException("年月格式不正确");
        }

        log.info("根据年月查询对应的预约设置数据:{}", month);
        try {
            List<OrderSetting> list = orderSettingService.getOrderSettingByMonth(month);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
        } catch (Exception e) {
            log.error("根据年月查询对应的预约设置数据失败: {}", e.getMessage(), e);
            throw new RuntimeException(MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    //下载模板
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadTemplate(@RequestParam("filename") String fileName) {
        try {
            // 从classpath加载文件
            Resource resource = new ClassPathResource("templates/" + fileName);
            if (!resource.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在".getBytes());
            }

            byte[] content = IOUtils.toByteArray(resource.getInputStream());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(content);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件读取失败".getBytes());
        }
    }

    //根据日期修改可预约人数
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting) {
        log.info("根据日期修改可预约人数:{}", orderSetting);
        try {
            orderSettingService.editNumberByOrderDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            log.error("根据日期修改可预约人数失败: {}", e.getMessage(), e);
            throw new RuntimeException(MessageConstant.ORDERSETTING_FAIL);
        }
    }

    //文件上传
    @PostMapping("/upload")
    public Result uploadExcel(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            log.info("文件上传:{}", excelFile.getOriginalFilename());
            // 调用业务逻辑层方法
            boolean result = orderSettingService.uploadExcel(excelFile);
            if (result) {
                return new Result(true, MessageConstant.ORDERSETTING_SUCCESS, null);
            } else {
                return new Result(false, MessageConstant.ORDERSETTING_FAIL, null);
            }
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return new Result(false, MessageConstant.ORDERSETTING_FAIL, null);
        }
    }

}
